package com.begye.smartloan.apptest.renzheng.lianxiren

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.allViews
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtRenZhengLianXiRenBinding
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.alldone.RenZhengAllDoneActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.dialog.FillItemEmptyFillDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemSelectListDialogFragment
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.renzheng.views.FillItemDoingHeader
import com.begye.smartloan.apptest.renzheng.views.FillItemInput
import com.begye.smartloan.apptest.renzheng.views.FillItemSelect
import com.begye.smartloan.apptest.renzheng.views.FillItemStatus
import com.begye.smartloan.apptest.renzheng.views.IFillItemResult
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import org.json.JSONArray
import org.json.JSONObject


@SuppressLint("CustomWelcomeScreen")
class RenZhengLianXiRenActivity : AppCompatActivity() {

    companion object {
        const val OPEN_SYS_LIAN_XI_REN_CODE = 5000
    }

    private lateinit var _binding: AtRenZhengLianXiRenBinding
    private lateinit var _fillSelectListDialogFragment: FillItemSelectListDialogFragment

    private val _renZhengLianXiRenViewModel by lazy {
        ViewModelProvider(this)[RenZhengLianXiRenViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtRenZhengLianXiRenBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configRemoteData()
    }

    private fun configYongHuLiuChengState() {

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoneFillLiveData.observe(this) {
            addDoneUI(it)
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenFillLiveData.observe(this) {
            val obj = it.first
            val sections = it.second
            for (index in sections.indices) {
                val list = sections[index]
                addDoingUI(obj, list, index)
            }
        }

        _yongHuLiuChengViewModel.onFutureFillLiveData.observe(this) {
            addFutureUI(it)
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = RenZhengAllDoneActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP,
                    params = hashMapOf<String, String>().apply {
                        put("titles", it)
                    }
                )
            }
        }
    }

    private fun configUIState() {

    }

    private fun configUIEvent() {

        _binding.atRenZhengNav.initConfig(
            text = getString(R.string.fill_text_3),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                if (LoginTool.filterAdType()) {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.atRenZhengDoingSubmit.setOnClickListener {
            combineParams()

            //
            addTouch(type = "ren_zheng_lian_xi_ren_commit_click")
        }

        _fillSelectListDialogFragment = FillItemSelectListDialogFragment()

    }

    private fun configRemoteData() {
        _yongHuLiuChengViewModel.requestYongHuLiuChengForLianXiRen()
    }

    private fun addDoneUI(value: List<JSONObject>? = null) {
        _binding.atRenZhengDoneContent.removeAllViews()

        value?.let { list ->
            for (index in list.indices) {
                val item = list[index]
                val fillItem = FillItemStatus(this)
                fillItem.initDataSource(item)
                fillItem.addCompleted(true)
                _binding.atRenZhengDoneContent.addView(fillItem)
            }
        }
    }

    private fun addDoingUI(
        obj: JSONObject? = null,
        value: List<JSONObject>? = null,
        sectionIndex: Int
    ) {

        if (sectionIndex == 0) {
            _binding.atRenZhengDoingContent.removeAllViews()
        }

        obj?.let { result ->
            val fillItemDoingHeader = FillItemDoingHeader(this)
            fillItemDoingHeader.hideContent(sectionIndex != 0)
            fillItemDoingHeader.addTag(result.optString("tag", ""))
            fillItemDoingHeader.addTitle(result.optString("title", ""))
            _binding.atRenZhengDoingContent.addView(fillItemDoingHeader)
        }

        value?.let { list ->
            // create new container
            val viewId = View.generateViewId()
            val containerLayout = LinearLayout(this).apply {
                id = viewId
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                orientation = LinearLayout.VERTICAL
            }

            for (index in list.indices) {
                val item = list[index]
                val action = item.optString("action", "")
                val values = item.optJSONArray("values") ?: JSONArray()

                if (action.contains("input", true)) {
                    val fillItem = FillItemInput(this)
                    fillItem.initDataSource(item)
                    containerLayout.addView(fillItem)

                } else if (action.contains("CONTACT_GROUP_RELATION", true)) {
                    val fillItem = FillItemSelect(this)
                    fillItem.initDataSource(item)
                    fillItem.addClickListener { fTag, fTitle ->
                        _renZhengLianXiRenViewModel.fts = System.currentTimeMillis()
                        _fillSelectListDialogFragment.apply {
                            addTitle(fTitle)
                            addDataSource(values)
                            addClickListener { _, jsonObject ->
                                val content = jsonObject.optString("value", "")
                                val bts = System.currentTimeMillis()
                                fillItem.updateValue(
                                    _renZhengLianXiRenViewModel.fts,
                                    bts,
                                    index+1,
                                    content
                                )
                            }
                            showNow(supportFragmentManager, fTag)
                        }
                    }
                    containerLayout.addView(fillItem)

                } else if (action.contains("CONTACT_GROUP_NAME", true)) {
                    val fillItem = FillItemSelect(this)
                    fillItem.initDataSource(item)
                    fillItem.showExtIcon(false)
                    fillItem.addClickListener { _, _ ->
                        val pIndex = OPEN_SYS_LIAN_XI_REN_CODE + sectionIndex
                        openSysLianXiRenUI(pIndex)
                    }
                    containerLayout.addView(fillItem)

                } else if (action.contains("CONTACT_GROUP_PHONE", true)) {
                    val fillItem = FillItemSelect(this)
                    fillItem.initDataSource(item)
                    fillItem.addExtIcon(R.drawable.dres_48)
                    fillItem.addClickListener { _, _ ->
                        val pIndex = OPEN_SYS_LIAN_XI_REN_CODE + sectionIndex
                        openSysLianXiRenUI(pIndex)
                    }
                    containerLayout.addView(fillItem)
                }
            }

            _binding.atRenZhengDoingContent.addView(containerLayout)
            _renZhengLianXiRenViewModel.updateContainerLayoutId("$sectionIndex", viewId)
        }
    }

    private fun addFutureUI(value: List<JSONObject>? = null) {
        _binding.atRenZhengFutureContent.removeAllViews()

        value?.let { list ->
            for (index in list.indices) {
                val item = list[index]
                val fillItem = FillItemStatus(this)
                fillItem.initDataSource(item)
                fillItem.addCompleted(false)
                _binding.atRenZhengFutureContent.addView(fillItem)
            }
        }
    }

    private fun combineParams() {
        val paramsList = mutableListOf<HashMap<String, Any>>()
        val viewIds = _renZhengLianXiRenViewModel.findAllContainers()
        var allItemsFilled = true
        for (viewId in viewIds) {
            val container = _binding.atRenZhengDoingContent.findViewById<LinearLayout>(viewId)
            if (container != null) {
                val subList = container.allViews
                val params = hashMapOf<String, Any>()
                for (view in subList) {
                    if (view is IFillItemResult) {
                        val tag = view.tag.toString().trim()
                        val result = view.calResult()
                        if (result.isBlank()) {
                            allItemsFilled = false
                        }
                        params[tag] = result
                    }
                }
                if (params.isNotEmpty()) {
                    paramsList.add(params)
                }
            }
        }

        if (paramsList.isNotEmpty() and allItemsFilled) {
            _yongHuLiuChengViewModel.requestUpdateYongHuLiuChengForLianXiRen(paramsList)
        } else {
            val dialog = FillItemEmptyFillDialogFragment()
            dialog.showNow(supportFragmentManager, "notFills")
        }
    }

    private fun hasMultipleValue(number: String): Boolean {
        try {
            val viewIds = _renZhengLianXiRenViewModel.findAllContainers()
            for (viewId in viewIds) {
                val container = _binding.atRenZhengDoingContent.findViewById<LinearLayout>(viewId)
                if (container != null) {
                    val subList = container.allViews
                    for (view in subList) {
                        if (view is IFillItemResult) {
                            val action = view.calAction()
                            if (action.contains("CONTACT_GROUP_PHONE", true)) {
                                val preValue = view.calResult(false)
                                if (preValue == number) return true
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            //
        }
        return false
    }

    private fun updateSelectValue(name: String, number: String, index: Int) {
        try {
            val viewId = _renZhengLianXiRenViewModel.findContainerLayout("$index")
            if (viewId != null) {
                val container = _binding.atRenZhengDoingContent.findViewById<LinearLayout>(viewId)
                if (container != null) {
                    val bts = System.currentTimeMillis()
                    val subList = container.allViews
                    for (view in subList) {
                        if (view is IFillItemResult) {
                            val action = view.calAction()
                            if (action.contains("CONTACT_GROUP_NAME", true)) {
                                view.updateValue(
                                    _renZhengLianXiRenViewModel.fts,
                                    bts,
                                    index+1,
                                    name
                                )
                            }
                            if (action.contains("CONTACT_GROUP_PHONE", true)) {
                                view.updateValue(
                                    _renZhengLianXiRenViewModel.fts,
                                    bts,
                                    index+1,
                                    number
                                )
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            //
        }
    }

    private fun openSysLianXiRenUI(reqCode: Int = OPEN_SYS_LIAN_XI_REN_CODE) {
        try {
            _renZhengLianXiRenViewModel.fts = System.currentTimeMillis()
            val intent =
                Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
            startActivityForResult(intent, reqCode)
        } catch (e: Exception) {
            //
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val isPickAction = (requestCode >= OPEN_SYS_LIAN_XI_REN_CODE)
        if (isPickAction && resultCode == RESULT_OK) {
            try {
                val dataIntent = data?.data ?: return

                val projection = arrayOf(
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                )

                contentResolver.query(dataIntent, projection, null, null, null)?.use { cursor ->
                    if (cursor.moveToFirst()) {
                        val phoneNumber = cursor.getString(
                            cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)
                        )
                        val displayName = cursor.getString(
                            cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                        )
                        if (phoneNumber.isBlank() or displayName.isBlank()) {
                            Toast.makeText(
                                this,
                                "Please select a contact",
                                Toast.LENGTH_LONG
                            ).show()
                            return
                        }

                        // check if has be select before
                        if (hasMultipleValue(phoneNumber)) {
                            Toast.makeText(
                                this,
                                "This contact did selected!",
                                Toast.LENGTH_LONG
                            ).show()
                            return
                        }

                        val pIndex = requestCode - OPEN_SYS_LIAN_XI_REN_CODE
                        updateSelectValue(displayName, phoneNumber, pIndex)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

